<?php
/*
 * @Author: 李志刚
 * @CopyRight: 2022-2099 李志刚（854378082@qq.com）
 * @Date: 2019-01-03 20:14:16
 * @Description: 管理员管理
 * @LastEditors: 李志刚
 * @LastEditTime: 2022-04-30 17:24:03
 * @FilePath: /CoinCMF/app/Http/Controllers/Console/Rbac/AdminController.php
 */

namespace App\Http\Controllers\Console\Rbac;


use App\Customize\Func;
use App\Exceptions\FireFlyException;
use App\Models\Rbac\Admin;
use Illuminate\Http\Request;
use App\Models\Rbac\RoleAdmin;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;
use App\Http\Requests\BatchRequest;
use App\Http\Requests\DetailRequest;
use App\Http\Requests\StatusRequest;
use App\Http\Requests\Ums\AdminPwdRequest;
use App\Http\Requests\Ums\AdminRequest;
use App\Http\Requests\Ums\AdminUpdateRequest;
use App\Http\Requests\Ums\AdminUpdateSelfRequest;
use App\Models\Rbac\DepartmentAdmin;
use Illuminate\Support\Facades\Validator;

class AdminController extends Controller
{
    public function getList(Request $request)
    {
        $key = $request->input('key','');
        $page = $request->input('page', 1);
        $size = $request->input('size', 10);
        $query = Admin::where(function ($q) use ($key) {
                    if ($key != '') {
                        $q->where('name', 'like', '%' . $key . '%');
                    }
                })->where('del_flag',0);
        $count = $query->count();
        $list = $query->limit($size)->offset(($page - 1) * $size)->orderBy('id','asc')->get();
        return $this->resJson(200,'成功', ['list' => $list, 'count' => $count]);
    }
    public function getDetail(DetailRequest $request)
    {
        $admin = Admin::findOrFail($request->input('detail_id'));
        $admin->department_ids = $admin->department->pluck('id');
        $admin->role_ids = $admin->role->pluck('id');
        return $this->resJson(200,'成功',$admin);
    }
    public function postCreate(AdminRequest $request)
    {
        DB::transaction(function() use($request){
            $data = $request->all();
            $crypt = Func::str_random(10);
            $pwd = Func::makepwd($data['password'],$crypt);
            $create = ['name'=>$data['name'],'realname'=>$data['realname'],'phone'=>$data['phone'],'email'=>$data['email'],'password'=>$pwd,'crypt'=>$crypt];
            $admin = Admin::create($create);
            $rids = $request->input('role_ids',[]);
            if (count($rids) > 0) {
                $rdata = [];
                foreach ($rids as $k) {
                    $rdata[] = ['role_id' => $k, 'admin_id' => $admin->id];
                }
                RoleAdmin::insert($rdata);
            }
            $department_ids = $request->input('department_ids',[]);
            if (count($department_ids) > 0) {
                $rdata = [];
                foreach ($department_ids as $k) {
                    $rdata[] = ['department_id' => $k, 'admin_id' => $admin->id];
                }
                DepartmentAdmin::insert($rdata);
            }
        });
        return $this->resJson(200,'成功');
    }
    public function postEditInfo(AdminUpdateRequest $request)
    {
        DB::transaction(function() use($request){
            $data = $request->all();
            $detail_id = $data['detail_id'];
            $update = ['realname'=>$data['realname'],'phone'=>$data['phone'],'email'=>$data['email']];
            Admin::where('id', $detail_id)->update($update);
            $rids = $request->input('role_ids',[]);
            // 先删除再添加
            RoleAdmin::where('admin_id', $detail_id)->delete();
            if(count($rids) > 0){
                $rdata = [];
                foreach ($rids as $k) {
                    $rdata[] = ['role_id'=>$k, 'admin_id'=> $detail_id];
                }
                RoleAdmin::insert($rdata);
            }
            // 先删除再添加
            DepartmentAdmin::where('admin_id', $detail_id)->delete();
            $department_ids = $request->input('department_ids',[]);
            if (count($department_ids) > 0) {
                $rdata = [];
                foreach ($department_ids as $k) {
                    $rdata[] = ['department_id' => $k, 'admin_id' => $detail_id];
                }
                DepartmentAdmin::insert($rdata);
            }
        });
        return $this->resJson(200,'成功');
    }
    public function postSelfEditInfo(AdminUpdateSelfRequest $request)
    {
        $data = $request->all();
        $detail_id = $data['detail_id'];
        $update = ['realname'=>$data['realname'],'phone'=>$data['phone'],'email'=>$data['email']];
        Admin::where('id', $detail_id)->update($update);
        return $this->resJson(200,'成功');
    }
    public function postEditPassword(AdminPwdRequest $request)
    {
        $data = $request->all();
        $detail_id = $data['detail_id'];
        $crypt = Func::str_random(10);
        $pwd = Func::makepwd($data['password'],$crypt);
        $update = ['password'=>$pwd,'crypt'=>$crypt];
        $user = Admin::find($detail_id);
        Admin::where('id', $detail_id)->update($update);
        Func::removeToken($user->name,'c-token');
        return $this->resJson(200,'成功');
    }
    public function postSelfEditPassword(AdminPwdRequest $request)
    {
        $data = $request->all();
        $detail_id = $data['detail_id'];
        $crypt = Func::str_random(10);
        $pwd = Func::makepwd($data['password'],$crypt);
        $update = ['password'=>$pwd,'crypt'=>$crypt];
        Admin::where('id', $detail_id)->update($update);
        $user = Admin::find($detail_id);
        Func::removeToken($user->name,'c-token');
        return $this->resJson(200,'成功');
    }
    public function postStatus(StatusRequest $request)
    {
        $data = $request->all();
        $detail_id = $data['detail_id'];
        $status = $data['status'];
        Admin::where('id', $detail_id)->update(['status'=>$status]);
        $user = Admin::find($detail_id);
        Func::removeToken($user->name,'c-token');
        return $this->resJson(200,'成功');
    }
    public function postRemove(BatchRequest $request)
    {
        $detail_id = $request->input('detail_id',[]);
        if(in_array(1,$detail_id)){
            throw new FireFlyException(403,'创始人不能删除！');
        }
        DB::transaction(function() use($detail_id){
            Admin::whereIn('id', $detail_id)->update(['del_flag'=>1]);
            RoleAdmin::where('admin_id', $detail_id)->delete();
            DepartmentAdmin::where('admin_id', $detail_id)->delete();
        });
        $admins = Admin::whereIn('id', $detail_id)->get();
        foreach ($admins as $v) {
            Func::removeToken($v->name,'c-token');
        }
        return $this->resJson(200,'成功');
    }
}
